package com.aitaoxue.palx.ui;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.InjectView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class AddNewBlogActivity extends BaseActivity {

	@InjectView(R.id.content1)
	EditText content1;
	@InjectView(R.id.content2)
	EditText content2;
	@InjectView(R.id.content3)
	EditText content3;
	@InjectView(R.id.content4)
	EditText content4;

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	protected int getActionBarTitle() {
		return R.string.add_new_blog;
	}

	@Override
	protected int getLayoutId() {
		return R.layout.add_new_blog;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public void initView() {

	}

	@Override
	public void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.push_blog, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add_blog:
			pushBlog();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void pushBlog() {
		if (isEmpty(content1) || isEmpty(content2) || isEmpty(content3)
				|| isEmpty(content4)) {
			showToast("请填完所有内容", 0, 0);
		} else {
			showWaitDialog();
			AitaoXueApi.joinRecords(getIntent().getStringExtra("orderid"),
					content1.getText().toString(), content2.getText()
							.toString(), content3.getText().toString(),
					content4.getText().toString(), mHandler);
		}
	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			hideWaitDialog();

			String res = new String(arg2);
			try {
				JSONObject json = new JSONObject(res);

				String msg = json.getString("codemsg");

				if (msg.equals("success")) {
					// showToast("发送成功", 0, 0);
					Toast.makeText(AddNewBlogActivity.this, "发送成功",
							Toast.LENGTH_SHORT).show();
					finish();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			// TODO Auto-generated method stub

		}
	};

	private boolean isEmpty(EditText content) {
		if (TextUtils.isEmpty(content.getText())) {
			return true;
		} else {
			return false;
		}
	}

}
